var ajaxURL = 'listServlet';
var pollInterval = 2000;

window.onload = function() {
    poll();
}

/* Poll Functions */

function poll() {
    //getTreeData();
    //getChatData();

    loop1 = setTimeout("getTreeData()", 1000);
    loop1 = setTimeout("getChatData()", 2000);
}

/* Poll Functions end */

/* AJAX Functions */

function initAjax() {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
	
    return xmlhttp;
}

/* End of AJAX Functions */

/* Cookie and misc. functions */

function getCookie(check_name) {
	// http://techpatterns.com/downloads/javascript_cookies.php
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) {
		return null;
	}
}

function getMyUserID() {
	return getCookie('ichat.username');
}

function roomMessageKeyPress(e, room) {
	// look for window.event in case event isn't passed in
	if (window.event) {
		e = window.event;
	}

	if (e.keyCode == 13 && document.getElementById('roomMessage_' + room).value != '') {
                //alert(document.getElementById('roomMessage_' + receiver).value);
		sendRoomChat(room);
	}
}


function chatMessageKeyPress(e, roomname, receiver) {
	// look for window.event in case event isn't passed in
	if (window.event) {
		e = window.event;
	}

	if (e.keyCode == 13 && document.getElementById('chatMessage_' + roomname + '_' + receiver).value != '') {
                //alert(document.getElementById('chatMessage_' + roomname + '_' + receiver).value)
		sendUserChat(receiver, roomname);
	}
}


/* Cookie and misc. functions End */

/* Tree Management Functions */

function getTreeData() {
    xmlhttp = initAjax();

    postdata = "action=getlist";

    xmlhttp.open("POST", ajaxURL, true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postdata.length);

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            response = xmlhttp.responseText;
            responseJSON = eval('(' + response + ')');
            buildTree(responseJSON);
        }
    }

    xmlhttp.send(postdata);

    loop = setTimeout("getTreeData()", pollInterval * 8);
}

function buildTree(data) {
    tree = document.createElement("div");
    tree.setAttribute("id", "sitemap");

    for(n in data['fakultas']) {
        nodeFakultas = document.createElement("li");
        nodeFakultas.setAttribute("id", "nodeFakultas_" + data['fakultas'][n]['idfakultas']);
        nodeFakultas.innerHTML = data['fakultas'][n]['nama'];

        ulNodeFakultas = document.createElement("ul");
        ulNodeFakultas.setAttribute("id", "ulNodeFakultas_" + data['fakultas'][n]['idfakultas']);
        ulNodeFakultas.setAttribute("style", "display: none;");

        spanNodeFakultas = document.createElement("span");
        spanNodeFakultas.setAttribute("class", "collapsed");

        nodeFakultas.appendChild(ulNodeFakultas);
        nodeFakultas.appendChild(spanNodeFakultas);
        tree.appendChild(nodeFakultas);
    }

    document.getElementById("sitemap").innerHTML = tree.innerHTML;

    for(n in data['prodi']) {
        nodeProdi = document.createElement("li");
        nodeProdi.setAttribute("id", "nodeProdi_" + data['prodi'][n]['idprodi']);
        nodeProdi.innerHTML = data['prodi'][n]['nama'];

        ulNodeProdi = document.createElement("ul");
        ulNodeProdi.setAttribute("id", "ulNodeProdi_" + data['prodi'][n]['idprodi']);
        ulNodeProdi.setAttribute("style", "display: none;")

        spanNodeProdi = document.createElement("span");
        spanNodeProdi.setAttribute("class", "collapsed");

        nodeProdi.appendChild(ulNodeProdi);
        nodeProdi.appendChild(spanNodeProdi);
        document.getElementById("ulNodeFakultas_" + data['prodi'][n]['idfakultas']).appendChild(nodeProdi);
    }

    for(n in data['room']) {
        nodeRoom = document.createElement("li");
        nodeRoom.setAttribute("onclick", "joinRoom('" + data['room'][n]['name'] + "')");
        nodeRoom.setAttribute("style", "cursor: pointer;");
        nodeRoom.innerHTML = "<a>" + data['room'][n]['name'] + "</a>";

        if(data['room'][n]['parenttype'] == "fakultas") {
            document.getElementById("ulNodeFakultas_" + data['room'][n]['parent']).appendChild(nodeRoom);
        } else {
            document.getElementById("ulNodeProdi_" + data['room'][n]['parent']).appendChild(nodeRoom);
        }
    }

    sitemapstyler();
}

/* Tree Management Functions End */

/* Chatroom Functions */

function updateChatWindow(type, sender, receiver, room, message) {
    // type:
    // 0: from myself
    // 1: from user
    // 2: from room
    // 3: server message
    
    switch(type) {
        case 0:
            target = 'chatText_' + room + '_' + receiver;
            from = getMyUserID();
            break;
        case 1:
            target = 'chatText_' + room + '_' + sender;
            from = sender;
            break;
        case 2:
            target = 'roomText_' + room;
            from = sender;
            break;
    }
    
    if(document.getElementById(target)) {
        x = document.getElementById(target);
        x.innerHTML += '<u>' + from + ':</u> ' + message + '<br />';
        x.scrollTop = x.scrollHeight;
    } else {
        if(document.getElementById('roomBox_' + room)) {
            addUserChatTab(room, sender);
            x = document.getElementById(target);
            x.innerHTML += '<u>' + from + ':</u> ' + message + '<br />';
            x.scrollTop = x.scrollHeight;
        }
    }
}

function sendUserChat(receiver, room) {
    xmlhttp = initAjax();

    postdata = 'action=senduserchat';
    postdata += '&sender=' + getMyUserID();
    postdata += '&receiver=' + receiver;
    postdata += '&room=' + room;
    postdata += '&message=' + document.getElementById('chatMessage_' + room + '_' + receiver).value;
    document.getElementById('chatMessage_' + room + '_' + receiver).value = "";

    xmlhttp.open("POST", "chatEngine", true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postdata.length);
    //xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            response = xmlhttp.responseText;
            responseJSON = eval('(' + response + ')');
            updateChatWindow(0, responseJSON['ack']['sender'], responseJSON['ack']['receiver'], responseJSON['ack']['room'], responseJSON['ack']['message']);
        }
    }

    xmlhttp.send(postdata);

}

function sendRoomChat(room) {
    xmlhttp = initAjax();

    postdata = 'action=sendroomchat';
    postdata += '&sender=' + getMyUserID();
    postdata += '&room=' + room;
    postdata += '&message=' + document.getElementById('roomMessage_' + room).value;
    document.getElementById('roomMessage_' + room).value = "";

    xmlhttp.open("POST", "chatEngine", true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postdata.length);
    //xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            response = xmlhttp.responseText;
            responseJSON = eval('(' + response + ')');
            //updateChatWindow(0, responseJSON['ack']['sender'], responseJSON['ack']['receiver'], responseJSON['ack']['room'], responseJSON['ack']['message']);
        }
    }

    xmlhttp.send(postdata);

}

function joinRoom(roomname) {
    if(document.getElementById("roomBox_" + roomname)) {
        return;
    }

    xmlhttp = initAjax();

    postdata = "action=joinroom&roomname=" + roomname;

    xmlhttp.open("POST", "chatEngine", true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postdata.length);

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            response = xmlhttp.responseText;
            responseJSON = eval('(' + response + ')');

            if(responseJSON['joinstatus'] == 'false') {
                alert("di BAN cuk");
            } else {
                // add tab room baru
                addChatRoomTab(roomname, responseJSON['roomdata']);
            }
        }
    }

    xmlhttp.send(postdata);
}

function exitRoom(roomname) {
    xmlhttp = initAjax();

    postdata = "action=exitroom&roomname=" + roomname;

    xmlhttp.open("POST", "chatEngine", true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postdata.length);

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            response = xmlhttp.responseText;

            parent = document.getElementById("roomBoxes");
            child = document.getElementById("roomBox_" + roomname);
            
            parent.removeChild(child);
        }
    }

    xmlhttp.send(postdata);
}

function exitChat(roomname, username) {
    parent = document.getElementById("chatBoxes");
    child = document.getElementById("chatBox_" + roomname + "_" + username);

    parent.removeChild(child);
}

function addChatRoomTab(roomname, roomdata) {
    if(document.getElementById("roomBox_" + roomname)) {

    } else {
        roomBox = document.createElement("div");
        roomBox.setAttribute("id", "roomBox_" + roomname);
        roomBox.setAttribute("class", "roomBox");

        roomTitle = document.createElement("div");
        roomTitle.setAttribute("id", "roomTitle_" + roomname);
        roomTitle.innerHTML = "#" + roomname;

        roomClose = document.createElement("div");
        roomClose.setAttribute("id", "roomClose_" + roomname);
        roomClose.setAttribute("onclick", "exitRoom('" + roomname + "')");
        roomClose.innerHTML = "X";

        roomUsers = document.createElement("div");
        roomUsers.setAttribute("id", "roomUsers_" + roomname);

        roomInterface = document.createElement("div");
        roomInterface.setAttribute("id", "roomInterface_" + roomname);

        roomText = document.createElement("div");
        roomText.setAttribute("id", "roomText_" + roomname);

        roomMessage = document.createElement("input");
        roomMessage.setAttribute("id", "roomMessage_" + roomname);
        roomMessage.setAttribute("onkeypress", "roomMessageKeyPress(event, '" + roomname + "');")
        roomMessage.setAttribute("type", "text");

        roomInterface.appendChild(roomText);
        roomInterface.appendChild(roomMessage);

        ulUsers = document.createElement("ul");
        ulUsers.setAttribute("id", "ulListUser_" + roomname);

        for(n in roomdata['userlist']) {
            liUsers = document.createElement("li");
            liUsers.setAttribute("class", "userMahasiswa");
            liUsers.setAttribute("id", "listUser_" + roomname + "_" + roomdata['userlist'][n]['username']);
            liUsers.setAttribute("onclick", "addUserChatTab('" + roomname + "', '" + roomdata['userlist'][n]['username'] + "')")
            liUsers.innerHTML = roomdata['userlist'][n]['username'];
            ulUsers.appendChild(liUsers);
        }

        roomUsers.appendChild(ulUsers);

        roomBox.appendChild(roomTitle);
        roomBox.appendChild(roomClose);
        roomBox.appendChild(roomUsers);
        roomBox.appendChild(roomInterface);

        document.getElementById("roomBoxes").appendChild(roomBox);
    }
}

function addUserChatTab(roomname, username) {
     if(document.getElementById("chatBox_" + roomname + "_" + username)) {

    } else {
        chatBox = document.createElement("div");
        chatBox.setAttribute("id", "chatBox_" + roomname + "_" + username);
        chatBox.setAttribute("class", "chatBox");

        chatTitle = document.createElement("div");
        chatTitle.setAttribute("id", "chatTitle_" + roomname + "_" + username);
        chatTitle.innerHTML =  roomname + "_" + username;

        chatClose = document.createElement("div");
        chatClose.setAttribute("id", "chatClose_" + roomname + "_" + username);
        chatClose.setAttribute("onclick", "exitChat('" + roomname + "', '" + username + "')");
        chatClose.innerHTML = "X";

        chatInterface = document.createElement("div");
        chatInterface.setAttribute("id", "chatInterface_" + roomname + "_" + username);

        chatText = document.createElement("div");
        chatText.setAttribute("id", "chatText_" + roomname + "_" + username);

        chatMessage = document.createElement("input");
        chatMessage.setAttribute("id", "chatMessage_" + roomname + "_" + username);
        chatMessage.setAttribute("onkeypress", "chatMessageKeyPress(event, '" + roomname + "', '" + username + "');")
        chatMessage.setAttribute("type", "text");

        chatInterface.appendChild(chatText);
        chatInterface.appendChild(chatMessage);

        chatBox.appendChild(chatTitle);
        chatBox.appendChild(chatClose);
        chatBox.appendChild(chatInterface);

        document.getElementById("chatBoxes").appendChild(chatBox);
    }
}

function getChatData() {
    xmlhttp = initAjax();

    postdata = 'action=poll';
    
    xmlhttp.open("POST", "chatEngine", true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postdata.length);

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            response = xmlhttp.responseText;
            responseJSON = eval('(' + response + ')');

            for(n in responseJSON['chatmessages']) {
                updateChatWindow(1, responseJSON['chatmessages'][n]['sender'], responseJSON['chatmessages'][n]['receiver'], responseJSON['chatmessages'][n]['room'], responseJSON['chatmessages'][n]['message'])
            }

            for(n in responseJSON['roommessages']) {
                updateChatWindow(2, responseJSON['roommessages'][n]['sender'], "", responseJSON['roommessages'][n]['room'], responseJSON['roommessages'][n]['message']);
            }

            for(n in responseJSON['roomusers']) {
                liUsers = document.createElement("li");
                liUsers.setAttribute("class", "userMahasiswa");
                liUsers.setAttribute("id", "listUser_" + responseJSON['roomusers'][n]['room'] + "_" + responseJSON['roomusers'][n]['username']);
                liUsers.setAttribute("onclick", "addUserChatTab('" + responseJSON['roomusers'][n]['room'] + "', '" + responseJSON['roomusers'][n]['username'] + "')")
                liUsers.innerHTML = responseJSON['roomusers'][n]['username'];

                if(document.getElementById("ulListUser_" + responseJSON['roomusers'][n]['room'])) {
                    if(!document.getElementById("listUser_" + responseJSON['roomusers'][n]['room'] + "_" + responseJSON['roomusers'][n]['username'])) {
                        document.getElementById("ulListUser_" + responseJSON['roomusers'][n]['room']).appendChild(liUsers);
                    }
                }
            }
        }
    }

    xmlhttp.send(postdata);

    loop = setTimeout("getChatData()", pollInterval);
}

/* Chatroom functions end */

/* test area */

function testtesttest() {
    
}

/* test area end */